﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Acl.WinFormHosting.Internal;

/// <summary>
/// WinForm后台任务和WinForm线程
/// </summary>
class WinFormsHostedService : IHostedService
{
    private readonly ILogger<WinFormsHostedService> logger;
    private readonly WinFormsThread winFormsThread;
    private readonly IWinFormsContext winFormsContext;

    public WinFormsHostedService(ILogger<WinFormsHostedService> logger, WinFormsThread winFormsThread, IWinFormsContext winFormsContext)
    {
        this.logger = logger;
        this.winFormsThread = winFormsThread;
        this.winFormsContext = winFormsContext;
    }

    /// <inheritdoc />
    public Task StartAsync(CancellationToken cancellationToken)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            return Task.CompletedTask;
        }
        winFormsThread.Start();
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        if (winFormsContext.IsRunning)
        {
            logger.LogDebug("Stopping WinForms application.");
            await winFormsContext.Dispatcher.InvokeAsync(() =>
            {
                // Graceful close, otherwise finalizes try to dispose forms.
                foreach (var form in Application.OpenForms.Cast<Form>().ToList())
                {
                    try
                    {
                        form.Close();
                        form.Dispose();
                    }
                    catch (Exception ex)
                    {
                        logger.LogWarning(ex, "Couldn't cleanup a Form");
                    }
                }
                Application.ExitThread();
            });


        }
    }
}
